package com.smasher.core.utils;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Display;

import androidx.core.hardware.display.DisplayManagerCompat;

import com.smasher.core.other.ApplicationContext;


/**
 * @author moyu
 */
public class DensityUtil {
    /**
     * 根据手机的分辨率dip --> px
     *
     * @param dpValue dpValue
     */
    public static int dip2px(float dpValue) {
        final float scale = getDisplayMetricsByResources().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * 根据手机的分辨率 px --> dp
     *
     * @param pxValue pxValue
     */
    public static int px2dip(float pxValue) {
        final float scale = getDisplayMetricsByResources().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率 sp --> px
     *
     * @param sp sp
     */
    public static float sp2px(float sp) {
        final float scale = getDisplayMetricsByResources().scaledDensity;
        return sp * scale;
    }

    /**
     * 手机的分辨率getDensity
     */
    public static float getDensity() {
        return getDisplayMetricsByResources().density;
    }

    /**
     * 获取屏幕宽度
     */
    public static int getScreenWidth() {
        DisplayMetrics dm = getDisplayMetricsByResources();
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高度
     */
    public static int getScreenHeight() {
        DisplayMetrics dm = getDisplayMetricsByResources();
        return dm.heightPixels;
    }


    private static DisplayMetrics getDisplayMetricsByResources() {
        Context context = ApplicationContext.getInstance();
        return context.getResources().getDisplayMetrics();
    }

    private Display getDisplay() {
        Context context = ApplicationContext.getInstance();
        DisplayManagerCompat displayManagerCompat = DisplayManagerCompat.getInstance(context);
        return displayManagerCompat.getDisplay(Display.DEFAULT_DISPLAY);
    }

    private DisplayMetrics getDisplayMetrics() {
        Display display = getDisplay();
        DisplayMetrics metric = new DisplayMetrics();
        if (display != null) {
            display.getRealMetrics(metric);
            return metric;
        }
        return null;
    }
}
